
package com.leyou.user.controller;

import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import com.leyou.user.pojo.Address;
import com.leyou.user.pojo.User;
import com.leyou.user.pojo.UserDetail;
import com.leyou.user.pojo.Useron;
import com.leyou.user.service.UserService;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@Controller
@EnableConfigurationProperties(JwtProperties.class)
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(@PathVariable("data") String data, @PathVariable(value = "type") Integer type) {
        Boolean aBoolean = this.userService.checkData(data, type);

        if(aBoolean==null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.ok(aBoolean);
    }
    @PostMapping("code")
    public ResponseEntity<Void> sendVerifyCode(String phone){
        System.out.println(phone);
        Boolean aBoolean = this.userService.sendVerifyCode(phone);
        if(aBoolean==null || !aBoolean){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR) ;
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, String code){
        Boolean register = this.userService.register(user.getUsername(), user.getPassword(), user.getPhone(), code);
        if(!register){
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return  new ResponseEntity<Void>(HttpStatus.CREATED);
    }

    @PostMapping("login")
    public ResponseEntity<User> queryUserByUsernameAndPassword(String username, String password){
        User user = this.userService.queryUserByUsernameAndPassword(username, password);
        if(user == null){
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(user);
    }

    @GetMapping("address")
    ResponseEntity<List<Address>> queryAddressByUid(@CookieValue("LY_TOKEN") String token) throws Exception {
        UserInfo info = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        Long id = info.getId();
        List<Address> addresses = userService.queryAddressByUid(id);
        if(addresses==null){
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        return ResponseEntity.ok(addresses);
    }


    /**
     * 添加收货地址信息
     * @param token
     * @param address
     * @return
     */
    @PostMapping("addAddress")
    public ResponseEntity<Void> addAddress(@CookieValue("LY_TOKEN") String token,@RequestBody Address address) {
        try {
            UserInfo info = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if (info == null) {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            address.setUid(info.getId());
            userService.addAddress(token, address);
            return new ResponseEntity<>(HttpStatus.CREATED);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 修改地址
     */
    @PutMapping("addAddress")
    public ResponseEntity<Void> editAddress(@RequestBody Address address){
        userService.editAddress(address);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }



    /**
     * 根据id查询地址
     * @param id
     * @return
     */

    @GetMapping("address/{id}")
    public ResponseEntity<Address> queryAddressById(@PathVariable("id")Long id){
        Address address = this.userService.queryAddressById(id);
        if(address==null){
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        return ResponseEntity.ok(address);

    }

    /**
     * 查询所有的地址信息
     */
    @GetMapping("query")
    public ResponseEntity<List<Address>> queryAddress(@CookieValue("LY_TOKEN") String token){
        try {
            UserInfo info = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if (info == null) {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            Long id = info.getId();
            List<Address> addressList = userService.queryAddresses(id);
            return ResponseEntity.ok(addressList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 设置默认地址
     */
    @PostMapping("setDefault/{id}")
    public ResponseEntity<Void> setDefaultAddress(@CookieValue("LY_TOKEN")String token,@PathVariable Long id){

        try {
            UserInfo info = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if (info == null) {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            Long uid =info.getId();
            userService.setDefault(uid,id);
            return new ResponseEntity<>(HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

    }

    /**
     * 删除地址
     */
    @DeleteMapping("deleteAdd/{id}")
    public ResponseEntity<Void> deleteAddress(@PathVariable("id") Long id){
        userService.deleteAddress(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);

    }

    @PostMapping("updateAddress")
    public ResponseEntity<Void> updateAddress(@CookieValue("LY_TOKEN") String token,@RequestBody Address address){
        try {
            UserInfo info = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if(info==null){
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            this.userService.updateAddress(address);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok().build();
    }
    @PostMapping("edit")
    public ResponseEntity<Boolean> edit(@RequestBody Useron useron){
        Boolean boo = userService.editUserpassword(useron);
        if(boo==null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.ok(boo);
    }

    @GetMapping("getPhone")
    public ResponseEntity<String> queryPhone(@CookieValue("LY_TOKEN")String token){
        UserInfo info = null;
        try {
            info = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if(info==null){
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            Long id = info.getId();
            String phone = userService.queryPhone(id);
            return ResponseEntity.ok(phone);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }


    /**
     *  验证手机验证码
     */
    @GetMapping("validcode")
    public ResponseEntity<Void> queryCode(@RequestParam("code") String code,@RequestParam("phone")String phone){
        Boolean boo = userService.queryCode(code, phone);
        if(boo){
            return new ResponseEntity<>(HttpStatus.CREATED);
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 修改手机号码
     */
    @PutMapping("editphone/{phone}")
    public ResponseEntity<Void> editPhone(@PathVariable("phone")String phone,@CookieValue("LY_TOKEN")String token){
        UserInfo info = null;
        try {
            info = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if(info==null){
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            Long id = info.getId();
            userService.editPhone(id,phone);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 添加昵称头像等用户详情
     * @param token
     * @param userDetail
     * @return
     */
    @PostMapping("userDetail")
    public ResponseEntity<Void> saveUserDetail(@CookieValue("LY_TOKEN") String token,@RequestBody UserDetail userDetail ){
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if (userInfo == null){
                return ResponseEntity.badRequest().build();
            }
            userDetail.setUid(userInfo.getId());
            this.userService.addUserDetail(userDetail);
            return new ResponseEntity<>(HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 判断是否登录，如果登录根据用户id查询userDetail
     * @param token
     * @return
     */
    @GetMapping("queryUserDetail")
    public ResponseEntity<UserDetail> queryUserDetailByUid(@CookieValue("LY_TOKEN") String token){
        UserInfo userInfo = null;
        try {
            userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if (userInfo == null){
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            Long uid = userInfo.getId();
            UserDetail userDetail = this.userService.queryUserDetailByUid(uid);
            return ResponseEntity.ok(userDetail);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

    }

    @PutMapping("userDetail")
    public ResponseEntity<UserDetail> editUserDetail(@CookieValue("LY_TOKEN") String token,@RequestBody UserDetail userDetail){
        this.userService.updateUserDetail(userDetail);
        return ResponseEntity.ok().build();
    }


}
